#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from threading import Thread

from scapy.all import sniff, get_if_list, sendp, Packet
from scapy.all import *
from scapy.all import Ether, TCP, IP
# from scapy.layers.http import *
from NDN_header_Interest import NDNInterest
from NDN_header_Data_v import NDNData
import hashlib
import binascii
import time

# ifname = "enp7s0f1"
ifname = "h2-eth0"
TYPE_NDN = 0x8624
content = 'Hello, world!'
content_hex = int(binascii.b2a_hex(content), 16)


def get_if():
    ifs = get_if_list()
    iface = None
    for i in get_if_list():
        if ifname in i:
            iface = i
            break
    if not iface:
        print ("Cannot find ifname interface")
        exit(1)
    return iface


def handle_pkt(pkt):
    iface = ifname
    print("got a packet")
    print(type(pkt[Ether].src))
    print(type(get_if_hwaddr(iface)))
    if pkt[Ether].type == 0x0800 and pkt[Ether].src != get_if_hwaddr(iface):
        print("got a IP packet")
        if IP in pkt and pkt[IP].proto == 6:
            print("got a HTTP")
            pkt.show2()
            ndn_name = "beijing0/bjtu0000/yulei000/index.ht"
            components = ndn_name.split('/', 4)
            components_hex = [0, 0, 0, 0]
            for i in range(0, 3 + 1):
                components_hex[i] = int(binascii.b2a_hex(components[i]), 16)

            # interest
            str_pkt_type = 'interest'
            # bind_layers(Ether, NDNInterest, type=TYPE_NDN)
            print("sending {} on interface {}".format(str_pkt_type, iface))
            pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff', type=0x8624)
            # pkt = pkt / IP(dst=addr) / TCP(dport=1234, sport=random.randint(49152, 65535)) / args.message
            pkt = pkt / NDNInterest(Component1=components_hex[0], Component2=components_hex[1],
                                    Component3=components_hex[2])

            pkt.show2()
            current_time = datetime.now()
            print("current_time:    " + str(current_time))
            sendp(pkt, count=1, iface=iface, verbose=False)


def sniffpkt():
    bind_layers(Ether, NDNInterest, type=TYPE_NDN)
    ifaces = list(filter(lambda i: ifname in i, os.listdir(
        '/sys/class/net/')))  # 迭代器i是入口参数，'eth' in i是函数体，从os.listdir('/sys/class/net/')中过滤出满足函数体的部分
    iface = ifaces[0]  # 返回第一个iface 即eth0
    print("sniffing on %s" % iface)
    sys.stdout.flush()  # 刷新缓冲区
    sniff(iface=iface,
          prn=lambda x: handle_pkt(x))  # 流量监控


def main():
    t1 = Thread(target=sniffpkt)
    t1.start()


if __name__ == '__main__':
    main()